/**
 * 关联员工
 */
import React, { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Form, Modal, ModalProps } from 'antd';

import UserSelect from '@/components/user-select';

import { store } from '@/store';

import { TargetType } from '@/enum';
import { roleAddByRole } from '@/services/base/jiaoseguanlijiaosexiangguanjiekou';

export type LinkProps = ModalProps & {};

export type LinkRef = {
  open: (data: {
    role: BASE.Role;
    list: BASE.OrgUserInfoVOduixiang[];
    onSuccess: () => void;
  }) => void;
};

const Link = ({ ...rest }: LinkProps, ref: React.Ref<LinkRef>) => {
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<LinkRef['open']>[0]>();
  const submit = useRequest(
    async (values) => {
      await roleAddByRole({} as ArgumentsType<typeof roleAddByRole>[0], [], {
        data: {
          roleId: args?.role?.id as number,
          userIds: (values.userIds as { id: number }[]).map((item) => item.id)
        }
      });

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success('操作成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (data) => {
        setOpen(true);
        setArgs(data);

        setTimeout(() => {
          form.setFieldsValue({
            userIds: data?.list?.map((item) => {
              return {
                ...item,
                type: [TargetType.用户]
              };
            })
          });
        });
      }
    };
  });

  const onClose = () => {
    if (submit.loading) {
      store.app?.message.error('请等待请求完成');

      return;
    }

    form.resetFields();
    setOpen(false);
  };

  return (
    <Modal
      title="关联员工"
      width={424}
      {...rest}
      open={open}
      onCancel={onClose}
      onOk={() => {
        form.submit();
      }}
      okButtonProps={{
        loading: submit.loading,
        disabled: submit.loading
      }}
    >
      <Form onFinish={submit.runAsync} form={form} layout="vertical">
        <Form.Item name="userIds" rules={[{ required: true, message: '请选择员工' }]}>
          <UserSelect mode="multiple" selectTypeList={[TargetType.用户]} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default forwardRef(Link) as (
  props: LinkProps & {
    ref?: React.Ref<LinkRef>;
  }
) => React.ReactElement;
